#version 320 es

precision highp float;
precision highp sampler2DShadow;

out mediump vec4 fragColor;

layout (location = 118) uniform mat4 LightProjMatrix;
layout (location = 119) uniform highp vec3 lightPos;
layout (location = 120) uniform highp vec3 cameraPos;

// uniform sampler2D shadowMap;
uniform sampler2DShadow shadowMap;
uniform sampler2D colorTex;

struct VSOut
{
    highp vec3 nor_vec;
    highp vec3 w_pos;
    highp vec2 uv;
};

in VSOut vsout;

void main()
{
    mediump vec4 object_color = texture(colorTex, vsout.uv);

    mediump vec4 light_color = vec4(0.5f, 0.5f, 0.5f, 1.0f);

    mediump float amient_factor = 1.2f;
    mediump float diffuse_factor = 5.0f;
    mediump float spec_factor = 1.6f;

    highp vec3 input_dir = normalize(lightPos - vsout.w_pos);
    highp vec3 to_camera = normalize(cameraPos - vsout.w_pos);

    //  环境光
    mediump vec4 amient = amient_factor * light_color;

    //  漫反射
    mediump float diffuse_rate = max(0.0f, dot(-input_dir, vsout.nor_vec));
    mediump vec4 diffuse = light_color * diffuse_factor * diffuse_rate;

    // 镜面反射
    highp vec3 reflect_dir = normalize(reflect(input_dir, vsout.nor_vec));
    highp vec3 h_dir = (-input_dir + to_camera) * 0.5f;

    mediump float specular_rate = max(0.0f, dot(vsout.nor_vec, h_dir)); // Blinn-Phong Shade
    mediump vec4 specular = spec_factor * light_color * pow(specular_rate, 16.0f);

    highp vec4 light_space_cord = LightProjMatrix * vec4(vsout.w_pos, 1.0);
    highp vec4 light_proj_cords = normalize(light_space_cord);

    light_proj_cords.z -= max(0.0002f * (1.0f - dot(normalize(vsout.nor_vec), input_dir)), 0.0001f); // 0.0001f * max(0.0f, dot(normalize(vsout.nor_vec), input_dir)); // 把 model 向灯源处移动，防止

    highp float shadow = textureProj(shadowMap, light_proj_cords);

    highp float shadow_value = 1.0f;

    if (shadow < 0.01f || dot(input_dir, vsout.nor_vec) < 0.0f)
    {
        shadow_value = 0.8f;
    }

    fragColor = object_color * (amient * shadow_value + diffuse * shadow_value + specular * shadow_value);
}
